Update utils.cpp - improve fromHexString #12
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
fromHexString function has been optimized by directly converting characters to bytes using bitwise operations and manual parsing within the loop, eliminating the use of
std::stoul
and reducing the creation of temporary objects to enhance performance.(hex_str.substr(i, 2)),
which involves both allocation and copying of two characters into a new string object for each byte of the input hex string. This is computationally costly, especially for long strings.std::stoul,
thusly saving time and memory by minimizing reallocations.Also... error handling.
By reserving the required amount of space in the vector upfront
(bytes.reserve(cleaned_hex.length() / 2)),
the function avoids the overhead associated with the vector's automatic resizing during the push_back operations.Normally, if you don’t reserve space, the vector may need to resize and copy its contents multiple times as it grows, depending on the implementation. Each resizing involves allocating new memory and copying the existing elements to the new space, which is computationally expensive. This significantly improves performance primarily by reducing dynamic memory allocations and eliminating redundant operations